package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class CommentsService {

    @DubboReference
    private CommentApi commentApi;
    @DubboReference
    private UserInfoApi userInfoApi;


    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private MqMessageService mqMessageService;


    /**
     * 发布评论
     *
     * @param movementId
     * @param comment
     */
    public void saveComments(String movementId, String comment) {
        //获取操作用户id
        Long userId = UserHolder.getUserId();

        //构造comment
        Comment comment1 = new Comment();
        comment1.setPublishId(new ObjectId(movementId));
        comment1.setCommentType(CommentType.COMMENT.getType());
        comment1.setContent(comment);
        comment1.setUserId(userId);
        comment1.setCreated(System.currentTimeMillis());
        //3、调用API保存评论
        Integer commentCount = commentApi.save(comment1);
        log.info("commentCount = " + commentCount);

    }

    /**
     * 分页查询评论列表
     *
     * @param movementId
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult findComments(String movementId, Integer page, Integer pagesize) {
        //调用api查询评论列表
        List<Comment> list = commentApi.findComments(movementId, CommentType.COMMENT, page, pagesize);
        //判断list是否存在
        if (CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        //提取所有用户id，调用api查询用户详情
        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        List<CommentVo> vos = new ArrayList<>();
        //构造vo对象
        for (Comment comment : list) {
            UserInfo userInfo = map.get(comment.getUserId());
            if (userInfo != null) {
                CommentVo vo = CommentVo.init(userInfo, comment);
                vos.add(vo);
            }

        }
        //构造返回值
        return new PageResult(page, pagesize, 0l, vos);

    }

    /**
     * 点赞
     *
     * @param movementId
     * @return
     */
    public Integer like(String movementId) {
        //调用API 查询用户是否已经点赞
        Boolean hasComment = commentApi.hasComment(movementId, UserHolder.getUserId(), CommentType.LIKE);
        //如果用户已经点赞，则抛出异常
        if (hasComment) {
            throw new BusinessException(ErrorResult.likeError());
        }
        //调用api 保存数据库到MongoDB
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setUserId(UserHolder.getUserId());
        comment.setCreated(System.currentTimeMillis());
        Integer count = commentApi.save(comment);
        //拼接redis的key 将用户的点赞数据存入redis
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().put(key, hashKey, "1");
        return count;

    }

    /**
     * 取消点赞
     *
     * @param movementId
     * @return
     */
    public Integer dislike(String movementId) {
        //调用API 查询用户是否已经点赞
        Boolean hasComment = commentApi.hasComment(movementId, UserHolder.getUserId(), CommentType.LIKE);
        //如果未点赞 抛出异常
        if (!hasComment) {
            throw new BusinessException(ErrorResult.disLikeError());
        }
        //调用API 删除数据 返回点赞数量
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setUserId(UserHolder.getUserId());
        Integer count = commentApi.delete(comment);
        //拼接redis的key 删除点赞状态
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(key, hashKey);

        return count;
    }

    /**
     * 喜欢
     *
     * @param movementId
     * @return
     */
    public Integer love(String movementId) {
        //调用API 查询用户是否已经喜欢
        Boolean hasComment = commentApi.hasComment(movementId, UserHolder.getUserId(), CommentType.LOVE);
        //如果用户已经喜欢，则抛出异常
        if (hasComment) {
            throw new BusinessException(ErrorResult.loveError());
        }
        //调用api 保存数据库到MongoDB
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LOVE.getType());
        comment.setUserId(UserHolder.getUserId());
        comment.setCreated(System.currentTimeMillis());
        Integer count = commentApi.save(comment);
        //拼接redis的key 将用户的喜欢数据存入redis
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LOVE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().put(key, hashKey, "1");
        return count;
    }

    /**
     * 取消喜欢
     *
     * @param movementId
     * @return
     */
    public Integer dislove(String movementId) {
        //调用API 查询用户是否已经喜欢
        Boolean hasComment = commentApi.hasComment(movementId, UserHolder.getUserId(), CommentType.LOVE);
        //如果未喜欢 抛出异常
        if (!hasComment) {
            throw new BusinessException(ErrorResult.disloveError());
        }
        //调用API 删除数据 返回喜欢数量
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LOVE.getType());
        comment.setUserId(UserHolder.getUserId());
        Integer count = commentApi.delete(comment);
        //拼接redis的key 删除喜欢状态
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LOVE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(key, hashKey);

        return count;
    }

    //给评论点赞
    public Integer likeComment(String commentId) {
        String key = Constants.MOVEMENTS_INTERACT_KEY + UserHolder.getUserId();
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + commentId;
        String flag = (String) redisTemplate.opsForHash().get(key, hashKey);
        if ("alreadyLike".equals(flag)){
            throw new BusinessException(ErrorResult.likeError());
        }
        Integer count = commentApi.likeComment(commentId);
        redisTemplate.opsForHash().put(key,hashKey,"alreadyLike");
        return count;
    }

    //取消评论点赞
    public Integer dislikeComment(String commentId) {
        String key =Constants.MOVEMENTS_INTERACT_KEY+UserHolder.getUserId();
        String hashKey =Constants.MOVEMENT_LIKE_HASHKEY+commentId;
        String flag=(String) redisTemplate.opsForHash().get(key,hashKey);
        if(!"alreadyLike".equals(flag)){
            throw new BusinessException(ErrorResult.error());
        }
        Integer count =commentApi.dislikeComment(commentId);
        redisTemplate.opsForHash().put(key,hashKey,"alreadyLike");
        return count;
    }
}
